<template>
  <div class="toExpressContainer">
    <el-card>
      <el-row>
        <el-col :span="6">
          <!-- 搜索 -->
          <el-input
            placeholder="请输入内容"
            v-model="search"
            clearable
            @change="searchClick"
          >
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="el-icon-search" @click="searchClick"
            >寄件搜索</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="danger" icon="el-icon-delete" @click="batchDelete"
            >批量删除</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="" icon="el-icon-plus" @click="add"
            >添加寄件</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-row :gutter="10">
        <!-- 表格 -->
        <el-table
          :data="sendInformation"
          style="width: 100%"
          ref="table"
          v-loading="loading"
        >
          <!-- 多选 -->
          <el-table-column type="selection" width="50"> </el-table-column>
          <el-table-column prop="sendId" label="寄件单号"> </el-table-column>
          <el-table-column prop="sendName" label="寄件人姓名">
          </el-table-column>
          <el-table-column prop="sendToName" label="收件人姓名">
          </el-table-column>
          <el-table-column
            prop="sendAddress"
            label="收件地址"
          ></el-table-column>
          <el-table-column
            prop="sendToMobile"
            label="收件人电话"
          ></el-table-column>
          <el-table-column
            prop="sendContent"
            label="寄件内容"
          ></el-table-column>
          <el-table-column prop="sendStatus" label="寄件状态">
            <template slot-scope="scope">
              <el-tag type="warning" v-if="scope.row.sendStatus === '0'"
                >处理中</el-tag
              >
              <el-tag type="success" v-else-if="scope.row.sendStatus === '1'"
                >已寄出</el-tag
              >
              <el-tag type="danger" v-else>状态未知</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="sendCreateTime"
            label="寄件创建时间"
            width="200px"
          ></el-table-column>
          <el-table-column prop="sendPay" label="订单支付情况">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.sendPay === '1'"
                >已支付</el-tag
              >
              <el-tag type="info" v-else>未支付</el-tag>
            </template>
          </el-table-column>
          <!-- 操作区 -->
          <el-table-column label="操作">
            <!-- 插槽 slot-scope="scope"-->
            <template slot-scope="scope">
              <el-button type="" size="small" @click="singleEdit(scope)"
                >编辑</el-button
              >
              <el-button type="danger" size="small" @click="singleDelete(scope)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!-- 分页 -->
      <!-- 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
       -->
      <el-row :gutter="10">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[8, 16, 24, 32]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="parseInt(totalNumber)"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @prev-click="handleCurrentChange"
          @next-click="handleCurrentChange"
        >
        </el-pagination>
      </el-row>
    </el-card>
    <!-- drawer -->
    <el-drawer
      :title="drawerTitle"
      :visible.sync="drawerVisible"
      direction="rtl"
      size="50%"
      clasee="drawer"
    >
      <!-- Form表单区域 -->
      <el-form
        :model="sendInformationForm"
        label-width="100px"
        :rules="rules"
        ref="form"
      >
        <el-form-item label="寄件单号">
          <el-input v-model="sendInformationForm.sendId" disabled></el-input>
        </el-form-item>
        <el-form-item label="寄件学/工号" prop="userId">
          <el-input
            v-model="sendInformationForm.userId"
            @change="inputChange"
          ></el-input>
        </el-form-item>
        <el-form-item label="收件人姓名" prop="sendToName">
          <el-input
            v-model="sendInformationForm.sendToName"
            @change="inputChange"
          ></el-input>
        </el-form-item>
        <el-form-item label="寄件地址" prop="sendAddress">
          <!-- 地址选择器 -->
          <el-cascader
            v-model="sendInformationForm.sendAddress"
            :options="options"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="sendAddress">
          <!-- 详细地址选择 -->
          <el-input
            class="sendAddressDetail"
            v-model="sendInformationForm.sendAddressDetail"
            placeholder="请输入详细地址"
            @change="inputChange"
          ></el-input>
        </el-form-item>
        <el-form-item label="收件人电话" prop="sendToMobile">
          <el-input
            v-model="sendInformationForm.sendToMobile"
            @change="inputChange"
          ></el-input>
        </el-form-item>
        <el-form-item label="寄件内容" prop="sendContent">
          <el-input
            v-model="sendInformationForm.sendContent"
            @change="inputChange"
          ></el-input>
        </el-form-item>
        <el-form-item label="寄件状态" prop="sendStatus">
          <!-- 单选框 -->
          <el-radio v-model="sendInformationForm.sendStatus" label="0"
            >处理中</el-radio
          >
          <el-radio v-model="sendInformationForm.sendStatus" label="1"
            >已寄出</el-radio
          >
        </el-form-item>
        <el-form-item label="支付状态" prop="sendPay">
          <!-- 单选框 -->
          <el-radio v-model="sendInformationForm.sendPay" label="0"
            >未付款</el-radio
          >
          <el-radio v-model="sendInformationForm.sendPay" label="1"
            >已付款</el-radio
          >
        </el-form-item>
        <el-form-item class="operation">
          <el-button type="" size="medium" @click="cancelDrawer"
            >取消</el-button
          >
          <el-button type="primary" size="medium " @click="confirmClick">{{
            drawerButton
          }}</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import axios from "axios";
import { regionData, CodeToText, TextToCode } from "element-china-area-data";
export default {
  name: "ToExpress",
  data() {
    return {
      // 加载
      loading: false,
      form: {},
      options: regionData,
      // 搜索框内容
      search: "",
      // 分页信息
      pageSize: "",
      currentPage: "",
      totalNumber: "",
      // 寄件数据表格
      sendInformation: [],
      // 抽屉
      drawerTitle: "",
      drawerVisible: false,
      drawerButton: "",
      // form表单
      sendInformationForm: {
        sendId: "",
        sendName: "",
        sendToName: "",
        sendAddress: "",
        sendToMobile: "",
        sendContent: "",
        sendStatus: "",
        sendPay: "",
        userId: "",
        sendAddressDetail: "",
      },
      // 校验
      rules: {
        sendId: [{ required: true, message: "不能为空", trigger: "blur" }],
        userId: [{ required: true, message: "不能为空", trigger: "blur" }],
        sendToName: [{ required: true, message: "不能为空", trigger: "blur" }],
        sendAddress: [{ required: true, message: "不能为空", trigger: "blur" }],
        sendToMobile: [
          { required: true, message: "不能为空", trigger: "blur" },
          {
            pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
            message: "手机号格式错误",
            trigger: "blur",
          },
        ],
        sendContent: [{ required: true, message: "不能为空", trigger: "blur" }],
        sendStatus: [{ required: true, message: "不能为空", trigger: "blur" }],
        sendCreateTime: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        sendPay: [{ required: true, message: "不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    // 初始化页码
    this.currentPage = 1;
    this.pageSize = 8;
    this.search = "";
    this.getSendData(this.currentPage, this.pageSize, this.search);
  },
  methods: {
    // 获取寄件数据
    async getSendData(currentPage, pageSize, search) {
      // 清空数据
      this.sendInformation = [];
      this.loading = true;
      // 发请求
      const { data: res } = await axios({
        method: "GET",
        url: `/api/send/getSendInformation/${currentPage}/${pageSize}`,
        params: {
          query: search,
        },
      });
      if (res.code == 200) {
        // 赋值给数据模型
        for (let i = 0; i < res.data.list.length; i++) {
          var item = {};
          item.sendAddress = res.data.list[i].sendAddress;
          item.sendContent = res.data.list[i].sendContent;
          item.sendCreateTime = res.data.list[i].sendCreateTime;
          item.sendId = res.data.list[i].sendId;
          item.sendName = res.data.list[i].sendName;
          item.sendStatus = res.data.list[i].sendStatus;
          item.sendToMobile = res.data.list[i].sendToMobile;
          item.sendToName = res.data.list[i].sendToName;
          item.userId = res.data.list[i].userId;
          item.sendPay = res.data.list[i].sendPay;
          this.sendInformation.push(item);
        }
        this.currentPage = res.data.pageNum;
        this.pageSize = res.data.pageSize;
        this.totalNumber = res.data.total;
        console.log(this.sendInformation);
      } else {
        this.$message.error("服务器错误，请稍后重试！");
      }
      this.loading = false;
    },
    // 搜索数据
    searchClick() {
      this.sendInformation = [];
      this.currentPage = 1;
      this.getSendData(this.currentPage, this.pageSize, this.search);
    },
    // 点击前后以及页码发生改变
    handleCurrentChange(e) {
      this.currentPage = e;
      this.getSendData(this.currentPage, this.pageSize, this.search);
    },
    // 一页显示条数发生改变
    handleSizeChange(e) {
      this.pageSize = e;
      this.getSendData(this.currentPage, this.pageSize, this.search);
    },
    // 批量删除
    batchDelete() {
      this.$confirm("此操作将永久删除该寄件单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 获取选中项
          const batchDeleteData = this.$refs.table.selection;
          if (batchDeleteData.length == 0) {
            this.$message.warning("请选择需要删除的选中项");
            return;
          }
          const { data: res } = await axios({
            method: "DELETE",
            url: "/api/send/batchDelete",
            data: batchDeleteData,
          });
          if (res.code == 200) {
            this.$message.success("批量删除成功");
            this.getSendData(this.currentPage, this.pageSize, this.search);
          } else {
            this.$message.error("服务器错误，请稍后重试！");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 单个删除
    singleDelete(scope) {
      this.$confirm("此操作将永久删除该寄件单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 执行删除
          const { data: res } = await axios({
            method: "DELETE",
            url: "/api/send/removeOne",
            params: {
              sendId: scope.row.sendId,
            },
          });
          if (res.code == 200) {
            this.$message.success("删除成功");
            this.getSendData(this.currentPage, this.pageSize, this.search);
          } else {
            this.$message.error("服务器错误，请稍后重试！");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 新增、编辑按钮
    confirmClick() {
      if (this.drawerButton == "编辑") {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            // 城市编码转变城市文本
            this.sendInformationForm.sendAddress = this.getCodeToText(
              "",
              this.sendInformationForm.sendAddress
            );
            const { data: res } = await axios({
              method: "PUT",
              url: "/api/send/update",
              data: this.sendInformationForm,
            });
            if (res.code == 200) {
              this.$message.success("更新信息成功");
              this.getSendData(this.currentPage, this.pageSize, this.search);
              this.drawerVisible = false;
            } else if (res.code == 403) {
              this.$message.warning("寄件用户不存在！请重新确认！");
            } else {
              this.$message.error("服务器错误，请稍后重试！");
            }
          } else {
            return;
          }
        });
      } else {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            // 城市编码转变城市文本
            this.sendInformationForm.sendAddress = this.getCodeToText(
              "",
              this.sendInformationForm.sendAddress
            );
            const load = this.$loading({
              lock: true,
              text: "可视化数据加载中，请稍后",
              spinner: "el-icon-loading",
              background: "rgba(0,0,0,0.02)",
              target: document.querySelector(".drawer"),
            });
            const { data: res } = await axios({
              method: "POST",
              url: "/api/send/add",
              data: this.sendInformationForm,
            });
            if (res.code == 200) {
              this.drawerVisible = false;
              this.$message.success("新增寄件单成功");
              this.getSendData(this.currentPage, this.pageSize, this.search);
            } else if (res.code == 403) {
              this.$message.warning("寄件用户不存在！请重新确认！");
            } else {
              this.$message.error("服务器错误，请稍后重试！");
            }
            load.close();
          } else {
            return;
          }
        });
      }
    },
    // 单个编辑
    async singleEdit(scope) {
      this.drawerTitle = "寄件单编辑";
      this.drawerVisible = true;
      this.drawerButton = "编辑";
      // 发请求数据回显
      const { data: res } = await axios({
        method: "GET",
        url: "/api/send/getDescData",
        params: {
          sendId: scope.row.sendId,
        },
      });
      if (res.code == 200) {
        // 数据回显
        console.log(res);
        this.sendInformationForm.sendId = res.data.sendId;
        this.sendInformationForm.sendContent = res.data.sendContent;
        this.sendInformationForm.sendCreateTime = res.data.sendCreateTime;
        this.sendInformationForm.sendId = res.data.sendId;
        this.sendInformationForm.sendName = res.data.sendName;
        this.sendInformationForm.sendPay = res.data.sendPay;
        this.sendInformationForm.sendToMobile = res.data.sendToMobile;
        this.sendInformationForm.sendToName = res.data.sendToName;
        this.sendInformationForm.userId = res.data.userId;
        // 省市区文字转数字回显
        var address = res.data.sendAddress.split(",")[0];
        var a1 = TextToCode[address.split("/")[0]].code;
        var a11 = address.split("/")[1];
        var a12 = address.split("/")[2];
        var a2 = TextToCode[address.split("/")[0]][a11].code;
        var a3 = TextToCode[address.split("/")[0]][a11][a12].code;
        this.sendInformationForm.sendAddress = [a1, a2, a3];
        this.sendInformationForm.sendAddressDetail =
          res.data.sendAddress.split(",")[1];
        this.sendInformationForm.sendStatus = res.data.sendStatus;
      } else {
        this.$message.error("数据获取失败，请稍后重试！");
      }
    },
    inputChange() {
      this.$forceUpdate();
    },
    // 新增
    add() {
      // 清除form表单
      this.sendInformationForm = {};
      // 设置对应属性
      this.drawerTitle = "寄件单新增";
      this.drawerVisible = true;
      this.drawerButton = "新增";
      // 清空表单
      // this.$nextTick(() => {
      //   this.$refs.form.resetFields();
      // });
    },
    // 点击取消按钮
    cancelDrawer() {
      this.drawerVisible = false;
    },
    // 工具类
    getCodeToText(codeStr, codeArray) {
      if (null === codeStr && null === codeArray) {
        return null;
      } else if (null === codeArray) {
        codeArray = codeStr.split(",");
      }

      let area = "";
      switch (codeArray.length) {
        case 1:
          area += CodeToText[codeArray[0]];
          break;
        case 2:
          area += CodeToText[codeArray[0]] + "/" + CodeToText[codeArray[1]];
          break;
        case 3:
          area +=
            CodeToText[codeArray[0]] +
            "/" +
            CodeToText[codeArray[1]] +
            "/" +
            CodeToText[codeArray[2]];
          break;
        default:
          break;
      }
      return area;
    },
  },
};
</script>

<style>
.el-cascader-panel {
  height: 300px;
}

/* 公共样式修改 */
.toExpressContainer {
  height: 100%;
  padding: 50px;
}
.toExpressContainer .el-card {
  margin-top: 0px;
  margin-right: 0px;
}
/* 处理表格间距 */
.toExpressContainer .el-card .el-row:nth-child(2) {
  margin-top: 30px;
}
/* 处理分页间距 */
.toExpressContainer .el-card .el-row:nth-child(3) {
  margin-top: 30px;
}
/* 抽屉的padding */
.toExpressContainer .el-drawer {
  padding: 30px;
}
/* 处理单选 */
.el-radio__input.is-checked .el-radio__inner {
  border-color: #ff84b4 !important;
  background-color: #ff84b4 !important;
}
.el-radio__inner:hover {
  border-color: #ff84b4 !important;
}
.el-radio__input.is-checked + .el-radio__label {
  color: #ff84b4 !important;
}
/* 处理时间框大小 */
.toExpressContainer .timeForToExpress .el-input__inner {
  border-radius: 5px;
  height: 40px !important;
}
.toExpressContainer .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 783px !important;
}
/* 处理按钮 */
.toExpressContainer .operation .el-button {
  width: 48% !important;
}
/* .toExpressContainer .sendAddressDetail {
  margin-left: 14px;
  width: 71% !important;
} */
.toExpressContainer .el-cascader .el-input .el-input__inner {
  width: 800px;
}
/* 级联菜单高度 */
.el-cascader-panel {
  height: 204px;
}
</style>